package com.cc.dlnalib;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import androidx.annotation.NonNull;

public class WifiUtils {

    /**
     * 检查网络是否可用
     *
     * @param context 上下文
     * @return 网络是否可用
     */
    public static boolean checkEnable(@NonNull Context context) {
        boolean i = false;
        ConnectivityManager connectivityManager = ((ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE));
        if (connectivityManager != null) {
            NetworkInfo localNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return (localNetworkInfo != null) && (localNetworkInfo.isAvailable());
        }
        return false;
    }

    /**
     * 将ip的整数形式转换成ip形式
     *
     * @param ipInt int Ip地址
     * @return 字符串ip地址
     */
    public static String int2ip(int ipInt) {
        return (ipInt & 0xFF) + "" +
                ((ipInt >> 8) & 0xFF) + "." +
                ((ipInt >> 16) & 0xFF) + "." +
                ((ipInt >> 24) & 0xFF);
    }

    /**
     * 获取当前ip地址
     *
     * @param context 上下文
     * @return ip地址
     */
    public static String getLocalIpAddress(@NonNull Context context) {
        try {
            WifiManager wifiManager = (WifiManager) context.getApplicationContext()
                    .getSystemService(Context.WIFI_SERVICE);
            if (wifiManager != null) {
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                int i = wifiInfo.getIpAddress();
                return int2ip(i);
            }
        } catch (Exception ex) {
            return " 获取IP出错鸟!!!!请保证是WIFI,或者请重新打开网络!\n" + ex.getMessage();
        }
        return null;
    }
}
